<template>
  <div class="fund-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>资金管理</h2>
      <p>水库资金预算、收支管理与财务监控</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon budget">
                <el-icon>
                  <Money />
                </el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ formatCurrency(totalBudget) }}</div>
                <div class="stats-label">年度预算总额</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon income">
                <el-icon>
                  <TrendCharts />
                </el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ formatCurrency(totalIncome) }}</div>
                <div class="stats-label">累计收入</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon expense">
                <el-icon>
                  <ShoppingCart />
                </el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ formatCurrency(totalExpense) }}</div>
                <div class="stats-label">累计支出</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon balance">
                <el-icon>
                  <Wallet />
                </el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ formatCurrency(balance) }}</div>
                <div class="stats-label">账户余额</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能标签页 -->
    <el-card class="main-content">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 预算管理 -->
        <el-tab-pane label="预算管理" name="budget">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="hover" style="margin-bottom: 8px">
              <el-form :model="budgetQuery" inline>
                <el-form-item label="预算年度">
                  <el-select v-model="budgetQuery.year" placeholder="请选择年度" clearable>
                    <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
                  </el-select>
                </el-form-item>
                <el-form-item label="预算类型">
                  <el-select v-model="budgetQuery.type" placeholder="请选择类型" clearable>
                    <el-option label="运营预算" value="operation" />
                    <el-option label="维护预算" value="maintenance" />
                    <el-option label="建设预算" value="construction" />
                    <el-option label="应急预算" value="emergency" />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="budgetQuery.status" placeholder="请选择状态" clearable>
                    <el-option label="草稿" value="draft" />
                    <el-option label="待审核" value="pending" />
                    <el-option label="已批准" value="approved" />
                    <el-option label="执行中" value="executing" />
                    <el-option label="已完成" value="completed" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchBudget">查询</el-button>
                  <el-button @click="resetBudgetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 操作按钮 -->
            <el-card shadow="never" style="margin-bottom: 8px;">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" plain icon="Plus" @click="addBudget">新增预算</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="success" plain icon="Download" @click="exportBudget">导出预算</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="info" plain icon="DataAnalysis" @click="budgetAnalysis">预算分析</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 预算表格 -->
            <el-card shadow="hover">
              <el-table :data="budgetList" border>
                <el-table-column prop="year" label="预算年度" width="100" />
                <el-table-column prop="name" label="预算名称" min-width="200" />
                <el-table-column prop="type" label="预算类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getBudgetTypeTagType(row.type)">
                      {{ getBudgetTypeLabel(row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="预算总额" width="150">
                  <template #default="{ row }">
                    <span class="amount-text">{{ formatCurrency(row.totalAmount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="usedAmount" label="已使用" width="150">
                  <template #default="{ row }">
                    <span class="amount-text">{{ formatCurrency(row.usedAmount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="remainingAmount" label="剩余预算" width="150">
                  <template #default="{ row }">
                    <span class="amount-text">{{ formatCurrency(row.remainingAmount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="progress" label="执行进度" width="120">
                  <template #default="{ row }">
                    <el-progress :percentage="row.progress" :color="getProgressColor(row.progress)" :stroke-width="8" />
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getBudgetStatusTagType(row.status)">
                      {{ getBudgetStatusLabel(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作" width="250" fixed="right">
                  <template #default="{ row }">
                    <el-button link type="primary" icon="View" @click="viewBudgetDetail(row)">查看</el-button>
                    <el-button link type="primary" icon="Edit" @click="editBudget(row)">编辑</el-button>
                    <el-button link type="danger" icon="Delete" @click="deleteBudget(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <Pagination :total="budgetPagination.total" v-model:page="budgetPagination.page"
                  v-model:limit="budgetPagination.pageSize" @pagination="handleBudgetPagination" />
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 收入管理 -->
        <el-tab-pane label="收入管理" name="income">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="never" style="margin-bottom: 8px;">
              <el-form :model="incomeQuery" inline>
                <el-form-item label="收入时间">
                  <el-date-picker v-model="incomeQuery.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="收入类型">
                  <el-select v-model="incomeQuery.type" placeholder="请选择类型" clearable>
                    <el-option label="水费收入" value="water_fee" />
                    <el-option label="电费收入" value="electricity_fee" />
                    <el-option label="政府补贴" value="government_subsidy" />
                    <el-option label="其他收入" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item label="收入来源">
                  <el-input v-model="incomeQuery.source" placeholder="请输入收入来源" clearable />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchIncome">查询</el-button>
                  <el-button @click="resetIncomeQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>


            <!-- 操作按钮 -->
            <el-card shadow="never" style="margin-bottom: 8px;">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" plain icon="Plus" @click="addIncome">新增收入</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="success" plain icon="Download" @click="exportIncome">导出收入</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 收入表格 -->
            <el-card shadow="hover">
              <el-table :data="incomeList" border>
                <el-table-column prop="date" label="收入日期" width="120" />
                <el-table-column prop="type" label="收入类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getIncomeTypeTagType(row.type)">
                      {{ getIncomeTypeLabel(row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="source" label="收入来源" min-width="150" />
                <el-table-column prop="amount" label="收入金额" width="150">
                  <template #default="{ row }">
                    <span class="amount-text income-amount">{{ formatCurrency(row.amount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="收入说明" min-width="200" />
                <el-table-column prop="operator" label="操作人" width="100" />
                <el-table-column prop="createTime" label="录入时间" width="180" />
                <el-table-column label="操作" width="240" fixed="right">
                  <template #default="{ row }">
                    <el-button link type="primary" icon="View" @click="viewIncomeDetail(row)">查看</el-button>
                    <el-button link type="primary" icon="Edit" @click="editIncome(row)">编辑</el-button>
                    <el-button link type="danger" icon="Delete" @click="deleteIncome(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <Pagination :total="incomePagination.total" v-model:page="incomePagination.page"
                  v-model:limit="incomePagination.pageSize" @pagination="handleIncomePagination" />
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 支出管理 -->
        <el-tab-pane label="支出管理" name="expense">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="never" style="margin-bottom: 8px;">
              <el-form :model="expenseQuery" inline>
                <el-form-item label="支出时间">
                  <el-date-picker v-model="expenseQuery.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="支出类型">
                  <el-select v-model="expenseQuery.type" placeholder="请选择类型" clearable>
                    <el-option label="人员工资" value="salary" />
                    <el-option label="设备维护" value="maintenance" />
                    <el-option label="材料采购" value="material" />
                    <el-option label="水电费" value="utility" />
                    <el-option label="其他支出" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item label="审批状态">
                  <el-select v-model="expenseQuery.approvalStatus" placeholder="请选择状态" clearable>
                    <el-option label="待审批" value="pending" />
                    <el-option label="已审批" value="approved" />
                    <el-option label="已拒绝" value="rejected" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchExpense">查询</el-button>
                  <el-button @click="resetExpenseQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 操作按钮 -->
            <el-card shadow="never" style="margin-bottom: 8px;">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" plain icon="Plus" @click="addExpense">新增支出</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="success" plain icon="Download" @click="exportExpense">导出支出</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 支出表格 -->
            <el-card shadow="hover">
              <el-table :data="expenseList" border>
                <el-table-column prop="date" label="支出日期" width="120" />
                <el-table-column prop="type" label="支出类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getExpenseTypeTagType(row.type)">
                      {{ getExpenseTypeLabel(row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="purpose" label="支出用途" min-width="200" />
                <el-table-column prop="amount" label="支出金额" width="150">
                  <template #default="{ row }">
                    <span class="amount-text expense-amount">{{ formatCurrency(row.amount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="approvalStatus" label="审批状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getApprovalStatusTagType(row.approvalStatus)">
                      {{ getApprovalStatusLabel(row.approvalStatus) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="applicant" label="申请人" width="100" />
                <el-table-column prop="approver" label="审批人" width="100" />
                <el-table-column prop="createTime" label="申请时间" width="180" />
                <el-table-column label="操作" width="250" fixed="right">
                  <template #default="{ row }">
                    <el-button link type="primary" icon="View" @click="viewExpenseDetail(row)">查看</el-button>
                    <el-button link type="primary" icon="Edit" @click="editExpense(row)">编辑</el-button>
                    <el-button v-if="row.approvalStatus === 'pending'" link type="success" icon="Check"
                      @click="approveExpense(row)">审批</el-button>
                    <el-button link type="danger" icon="Delete" @click="deleteExpense(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <Pagination :total="expensePagination.total" v-model:page="expensePagination.page"
                  v-model:limit="expensePagination.pageSize" @pagination="handleExpensePagination" />
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 财务报表 -->
        <el-tab-pane label="财务报表" name="report">
          <div class="tab-content">
            <!-- 报表筛选 -->
            <el-card shadow="never" style="margin-bottom: 8px;">
              <el-form :model="reportQuery" inline>
                <el-form-item label="报表类型">
                  <el-select v-model="reportQuery.type" placeholder="请选择报表类型">
                    <el-option label="月度报表" value="monthly" />
                    <el-option label="季度报表" value="quarterly" />
                    <el-option label="年度报表" value="yearly" />
                  </el-select>
                </el-form-item>
                <el-form-item label="报表期间">
                  <el-date-picker v-model="reportQuery.period" :type="getDatePickerType()" placeholder="请选择期间"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="generateReport">生成报表</el-button>
                  <el-button type="success" @click="exportReport">导出报表</el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 报表图表 -->
            <div class="report-charts" style="margin-bottom: 8px;">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card title="收支趋势图">
                    <div id="incomeExpenseChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card title="支出分类占比">
                    <div id="expensePieChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
              </el-row>
            </div>

            <!-- 报表数据 -->
            <div class="report-data">
              <el-card title="财务汇总">
                <el-descriptions :column="3" border>
                  <el-descriptions-item label="总收入">
                    <span class="amount-text income-amount">{{ formatCurrency(reportData.totalIncome) }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="总支出">
                    <span class="amount-text expense-amount">{{ formatCurrency(reportData.totalExpense) }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="净收益">
                    <span class="amount-text" :class="reportData.netIncome >= 0 ? 'income-amount' : 'expense-amount'">
                      {{ formatCurrency(reportData.netIncome) }}
                    </span>
                  </el-descriptions-item>
                  <el-descriptions-item label="预算执行率">
                    <el-progress :percentage="reportData.budgetExecutionRate"
                      :color="getProgressColor(reportData.budgetExecutionRate)" />
                  </el-descriptions-item>
                  <el-descriptions-item label="资金使用效率">
                    <el-rate v-model="reportData.fundEfficiency" disabled show-score text-color="#ff9900" />
                  </el-descriptions-item>
                  <el-descriptions-item label="财务健康度">
                    <el-tag :type="getHealthTagType(reportData.financialHealth)">
                      {{ reportData.financialHealth }}
                    </el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 对话框组件 -->
    <FundFormDialog v-model="formDialogVisible" :fund-data="currentFundData" :dialog-type="dialogType"
      :form-type="currentFormType" @confirm="handleFormConfirm" />

    <FundDetailDialog v-model="detailDialogVisible" :fund-data="currentFundData" :detail-type="currentFormType"
      @edit="handleEdit" />

    <!-- 报表对话框 -->
    <ReportDialog v-model="reportDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Money,
  TrendCharts,
  ShoppingCart,
  Wallet,
  Plus,
  Download,
  DataAnalysis,
  View,
  Edit,
  Delete,
  Check
} from '@element-plus/icons-vue'
import FundFormDialog from './components/FundFormDialog.vue'
import FundDetailDialog from './components/FundDetailDialog.vue'
import ReportDialog from './components/ReportDialog.vue'
import Pagination from '@/components/Pagination/index.vue'
import * as echarts from 'echarts'

// 页面数据
const activeTab = ref('budget')
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const reportDialogVisible = ref(false)
const currentFundData = ref(null)
const dialogType = ref('add')
const currentFormType = ref('budget')

// 统计数据
const totalBudget = ref(50000000)
const totalIncome = ref(32000000)
const totalExpense = ref(28000000)
const balance = computed(() => totalIncome.value - totalExpense.value)

// 年度选项
const yearOptions = ref([2024, 2023, 2022, 2021, 2020])

// 预算管理
const budgetQuery = reactive({
  year: null,
  type: '',
  status: ''
})

const budgetList = ref([])

const budgetPagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 收入管理
const incomeQuery = reactive({
  dateRange: [],
  type: '',
  source: ''
})

const incomeList = ref([])

const incomePagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 支出管理
const expenseQuery = reactive({
  dateRange: [],
  type: '',
  approvalStatus: ''
})

const expenseList = ref([])

const expensePagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 加载预算数据（10-50条）
const loadBudgetData = async () => {
  await new Promise(resolve => setTimeout(resolve, 200))
  const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
  const types = ['operation', 'maintenance', 'construction', 'emergency']
  const statuses = ['draft', 'pending', 'approved', 'executing', 'completed']
  const count = randInt(10, 50)
  const list: any[] = []
  for (let i = 0; i < count; i++) {
    const year = [2024, 2023, 2022][randInt(0, 2)]
    const totalAmount = randInt(3_000_000, 20_000_000)
    const usedAmount = randInt(0, totalAmount)
    const remainingAmount = totalAmount - usedAmount
    const progress = Math.floor((usedAmount / totalAmount) * 100)
    list.push({
      id: i + 1,
      year,
      name: `预算-${i + 1}`,
      type: types[randInt(0, types.length - 1)],
      totalAmount,
      usedAmount,
      remainingAmount,
      progress,
      status: statuses[randInt(0, statuses.length - 1)],
      createTime: `${year}-${String(randInt(1, 12)).padStart(2, '0')}-${String(randInt(1, 28)).padStart(2, '0')} ${String(randInt(8, 18)).padStart(2, '0')}:30:00`
    })
  }
  budgetList.value = list
  budgetPagination.total = list.length
}

// 加载收入数据（10-50条）
const loadIncomeData = async () => {
  await new Promise(resolve => setTimeout(resolve, 200))
  const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
  const types = ['water_fee', 'electricity_fee', 'government_subsidy', 'other']
  const sources = ['城市供水公司', '电力公司', '水利局', '企业捐赠', '其他']
  const operators = ['张三', '李四', '王五', '赵六']
  const count = randInt(10, 50)
  const list: any[] = []
  for (let i = 0; i < count; i++) {
    const date = `2024-${String(randInt(1, 12)).padStart(2, '0')}-${String(randInt(1, 28)).padStart(2, '0')}`
    const amount = randInt(50_000, 5_000_000)
    list.push({
      id: i + 1,
      date,
      type: types[randInt(0, types.length - 1)],
      source: sources[randInt(0, sources.length - 1)],
      amount,
      description: `收入说明-${i + 1}`,
      operator: operators[randInt(0, operators.length - 1)],
      createTime: `${date} ${String(randInt(8, 18)).padStart(2, '0')}:${String(randInt(0, 59)).padStart(2, '0')}:00`
    })
  }
  incomeList.value = list
  incomePagination.total = list.length
}

// 加载支出数据（10-50条）
const loadExpenseData = async () => {
  await new Promise(resolve => setTimeout(resolve, 200))
  const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
  const types = ['salary', 'maintenance', 'material', 'utility', 'other']
  const applicants = ['人事部', '工程部', '采购部', '运行部']
  const approvers = ['财务总监', '技术总监', '经理']
  const statuses = ['pending', 'approved', 'rejected']
  const count = randInt(10, 50)
  const list: any[] = []
  for (let i = 0; i < count; i++) {
    const date = `2024-${String(randInt(1, 12)).padStart(2, '0')}-${String(randInt(1, 28)).padStart(2, '0')}`
    const amount = randInt(20_000, 1_000_000)
    const status = statuses[randInt(0, statuses.length - 1)]
    list.push({
      id: i + 1,
      date,
      type: types[randInt(0, types.length - 1)],
      purpose: `支出用途-${i + 1}`,
      amount,
      approvalStatus: status,
      applicant: applicants[randInt(0, applicants.length - 1)],
      approver: status === 'approved' ? approvers[randInt(0, approvers.length - 1)] : '',
      createTime: `${date} ${String(randInt(8, 18)).padStart(2, '0')}:${String(randInt(0, 59)).padStart(2, '0')}:00`
    })
  }
  expenseList.value = list
  expensePagination.total = list.length
}

// 财务报表
const reportQuery = reactive({
  type: 'monthly',
  period: null
})

const reportData = reactive({
  totalIncome: 4300000,
  totalExpense: 3800000,
  netIncome: 500000,
  budgetExecutionRate: 76,
  fundEfficiency: 4.2,
  financialHealth: '良好'
})

// 格式化货币
const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  }).format(amount)
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 30) return '#67c23a'
  if (percentage < 70) return '#e6a23c'
  return '#f56c6c'
}

// 预算相关方法
const getBudgetTypeTagType = (type: string) => {
  const typeMap = {
    'operation': '',
    'maintenance': 'success',
    'construction': 'warning',
    'emergency': 'danger'
  }
  return typeMap[type] || ''
}

const getBudgetTypeLabel = (type: string) => {
  const typeMap = {
    'operation': '运营预算',
    'maintenance': '维护预算',
    'construction': '建设预算',
    'emergency': '应急预算'
  }
  return typeMap[type] || type
}

const getBudgetStatusTagType = (status: string) => {
  const statusMap = {
    'draft': 'info',
    'pending': 'warning',
    'approved': 'success',
    'executing': '',
    'completed': 'success'
  }
  return statusMap[status] || ''
}

const getBudgetStatusLabel = (status: string) => {
  const statusMap = {
    'draft': '草稿',
    'pending': '待审核',
    'approved': '已批准',
    'executing': '执行中',
    'completed': '已完成'
  }
  return statusMap[status] || status
}

// 收入相关方法
const getIncomeTypeTagType = (type: string) => {
  const typeMap = {
    'water_fee': 'success',
    'electricity_fee': 'warning',
    'government_subsidy': '',
    'other': 'info'
  }
  return typeMap[type] || ''
}

const getIncomeTypeLabel = (type: string) => {
  const typeMap = {
    'water_fee': '水费收入',
    'electricity_fee': '电费收入',
    'government_subsidy': '政府补贴',
    'other': '其他收入'
  }
  return typeMap[type] || type
}

// 支出相关方法
const getExpenseTypeTagType = (type: string) => {
  const typeMap = {
    'salary': 'success',
    'maintenance': 'warning',
    'material': 'info',
    'utility': '',
    'other': 'info'
  }
  return typeMap[type] || ''
}

const getExpenseTypeLabel = (type: string) => {
  const typeMap = {
    'salary': '人员工资',
    'maintenance': '设备维护',
    'material': '材料采购',
    'utility': '水电费',
    'other': '其他支出'
  }
  return typeMap[type] || type
}

const getApprovalStatusTagType = (status: string) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || ''
}

const getApprovalStatusLabel = (status: string) => {
  const statusMap = {
    'pending': '待审批',
    'approved': '已审批',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 报表相关方法
const getDatePickerType = () => {
  const typeMap = {
    'monthly': 'month',
    'quarterly': 'month',
    'yearly': 'year'
  }
  return typeMap[reportQuery.type] || 'month'
}

const getHealthTagType = (health: string) => {
  const healthMap = {
    '优秀': 'success',
    '良好': '',
    '一般': 'warning',
    '较差': 'danger'
  }
  return healthMap[health] || ''
}

// 标签页切换
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
}

// 预算管理方法
const searchBudget = () => {
  ElMessage.info('查询预算数据...')
}

const resetBudgetQuery = () => {
  Object.assign(budgetQuery, {
    year: null,
    type: '',
    status: ''
  })
}

const addBudget = () => {
  currentFundData.value = null
  dialogType.value = 'add'
  currentFormType.value = 'budget'
  formDialogVisible.value = true
}

const editBudget = (row: any) => {
  currentFundData.value = row
  dialogType.value = 'edit'
  currentFormType.value = 'budget'
  formDialogVisible.value = true
}

const viewBudgetDetail = (row: any) => {
  currentFundData.value = row
  currentFormType.value = 'budget'
  detailDialogVisible.value = true
}

const deleteBudget = (row: any) => {
  ElMessageBox.confirm('确定要删除这个预算吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const exportBudget = () => {
  ElMessage.info('导出预算数据...')
}

const budgetAnalysis = () => {
  ElMessage.info('预算分析功能开发中...')
}

// 收入管理方法
const searchIncome = () => {
  ElMessage.info('查询收入数据...')
}

const resetIncomeQuery = () => {
  Object.assign(incomeQuery, {
    dateRange: [],
    type: '',
    source: ''
  })
}

const addIncome = () => {
  currentFundData.value = null
  dialogType.value = 'add'
  currentFormType.value = 'income'
  formDialogVisible.value = true
}

const editIncome = (row: any) => {
  currentFundData.value = row
  dialogType.value = 'edit'
  currentFormType.value = 'income'
  formDialogVisible.value = true
}

const viewIncomeDetail = (row: any) => {
  currentFundData.value = row
  currentFormType.value = 'income'
  detailDialogVisible.value = true
}

const deleteIncome = (row: any) => {
  ElMessageBox.confirm('确定要删除这条收入记录吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const exportIncome = () => {
  ElMessage.info('导出收入数据...')
}

// 支出管理方法
const searchExpense = () => {
  ElMessage.info('查询支出数据...')
}

const resetExpenseQuery = () => {
  Object.assign(expenseQuery, {
    dateRange: [],
    type: '',
    approvalStatus: ''
  })
}

const addExpense = () => {
  currentFundData.value = null
  dialogType.value = 'add'
  currentFormType.value = 'expense'
  formDialogVisible.value = true
}

const editExpense = (row: any) => {
  currentFundData.value = row
  dialogType.value = 'edit'
  currentFormType.value = 'expense'
  formDialogVisible.value = true
}

const viewExpenseDetail = (row: any) => {
  currentFundData.value = row
  currentFormType.value = 'expense'
  detailDialogVisible.value = true
}

const approveExpense = (row: any) => {
  ElMessageBox.confirm('确定要审批通过这笔支出吗？', '确认审批', {
    confirmButtonText: '通过',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.approvalStatus = 'approved'
    row.approver = '当前用户'
    ElMessage.success('审批成功')
  })
}

const deleteExpense = (row: any) => {
  ElMessageBox.confirm('确定要删除这条支出记录吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const exportExpense = () => {
  ElMessage.info('导出支出数据...')
}

// 图表实例
const incomeExpenseChart = ref(null)
const expensePieChart = ref(null)

// 图表数据
const chartData = reactive({
  incomeExpenseTrend: {
    months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    income: [280, 320, 450, 380, 520, 680, 750, 620, 580, 720, 650, 800],
    expense: [220, 280, 350, 320, 420, 580, 650, 520, 480, 620, 580, 720]
  },
  expenseCategory: [
    { name: '人员工资', value: 4500000, color: '#5470c6' },
    { name: '设备维护', value: 3200000, color: '#91cc75' },
    { name: '材料采购', value: 2800000, color: '#fac858' },
    { name: '水电费', value: 1500000, color: '#ee6666' },
    { name: '其他支出', value: 1000000, color: '#73c0de' }
  ]
})

// 初始化收支趋势图
const initIncomeExpenseChart = () => {
  const chartDom = document.getElementById('incomeExpenseChart')
  if (!chartDom) {
    console.warn('收支趋势图容器未找到')
    return
  }
  
  // 销毁已存在的图表实例
  if (incomeExpenseChart.value) {
    incomeExpenseChart.value.dispose()
  }
  
  // 确保容器有明确的尺寸
  const containerWidth = chartDom.offsetWidth || chartDom.clientWidth
  const containerHeight = chartDom.offsetHeight || chartDom.clientHeight
  
  if (containerWidth === 0 || containerHeight === 0) {
    console.warn('图表容器尺寸为0，延迟重试')
    setTimeout(() => initIncomeExpenseChart(), 200)
    return
  }
  
  incomeExpenseChart.value = echarts.init(chartDom, null, {
    width: containerWidth,
    height: containerHeight
  })
  
  const option = {
    title: {
      text: '收支趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#303133'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        if (!params || params.length === 0) return ''
        let result = params[0].name + '<br/>'
        params.forEach(param => {
          if (param && param.value !== undefined) {
            const value = (param.value / 10000).toFixed(1)
            result += `${param.marker}${param.seriesName}: ${value}万元<br/>`
          }
        })
        return result
      }
    },
    legend: {
      data: ['收入', '支出'],
      top: 30,
      textStyle: {
        color: '#606266'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.incomeExpenseTrend.months || [],
      axisLabel: {
        color: '#909399'
      },
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function(value) {
          return (value / 10000).toFixed(0) + '万'
        },
        color: '#909399'
      },
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f0f2f5'
        }
      }
    },
    series: [
      {
        name: '收入',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3
        },
        areaStyle: {
          opacity: 0.3
        },
        emphasis: {
          focus: 'series'
        },
        data: chartData.incomeExpenseTrend.income || [],
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: '支出',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3
        },
        areaStyle: {
          opacity: 0.3
        },
        emphasis: {
          focus: 'series'
        },
        data: chartData.incomeExpenseTrend.expense || [],
        itemStyle: {
          color: '#f56c6c'
        }
      }
    ]
  }
  
  incomeExpenseChart.value.setOption(option)
}

// 初始化支出分类饼图
const initExpensePieChart = () => {
  const chartDom = document.getElementById('expensePieChart')
  if (!chartDom) {
    console.warn('支出分类饼图容器未找到')
    return
  }
  
  // 销毁已存在的图表实例
  if (expensePieChart.value) {
    expensePieChart.value.dispose()
  }
  
  // 确保容器有明确的尺寸
  const containerWidth = chartDom.offsetWidth || chartDom.clientWidth
  const containerHeight = chartDom.offsetHeight || chartDom.clientHeight
  
  if (containerWidth === 0 || containerHeight === 0) {
    console.warn('图表容器尺寸为0，延迟重试')
    setTimeout(() => initExpensePieChart(), 200)
    return
  }
  
  expensePieChart.value = echarts.init(chartDom, null, {
    width: containerWidth,
    height: containerHeight
  })
  
  const option = {
    title: {
      text: '支出分类统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#303133'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        if (!params || params.value === undefined) return ''
        const value = (params.value / 10000).toFixed(1)
        return `${params.name}<br/>${params.marker}金额: ${value}万元<br/>占比: ${params.percent}%`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      textStyle: {
        color: '#606266'
      }
    },
    series: [
      {
        name: '支出分类',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
            formatter: function(params) {
              if (!params || params.value === undefined) return ''
              const value = (params.value / 10000).toFixed(1)
              return `${params.name}\n${value}万元`
            }
          }
        },
        labelLine: {
          show: false
        },
        data: (chartData.expenseCategory || []).map(item => ({
          value: item.value || 0,
          name: item.name || '',
          itemStyle: {
            color: item.color || '#5470c6'
          }
        }))
      }
    ]
  }
  
  expensePieChart.value.setOption(option)
}

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    setTimeout(() => {
      initIncomeExpenseChart()
      initExpensePieChart()
    }, 100) // 延迟100ms确保DOM完全渲染
  })
}

// 窗口大小改变时重新调整图表大小
const handleResize = () => {
  if (incomeExpenseChart.value) {
    // 获取容器的实际尺寸
    const chartDom = document.getElementById('incomeExpenseChart')
    if (chartDom) {
      const containerWidth = chartDom.offsetWidth || chartDom.clientWidth
      const containerHeight = chartDom.offsetHeight || chartDom.clientHeight
      
      if (containerWidth > 0 && containerHeight > 0) {
        incomeExpenseChart.value.resize({
          width: containerWidth,
          height: containerHeight
        })
      }
    }
  }
  
  if (expensePieChart.value) {
    // 获取容器的实际尺寸
    const chartDom = document.getElementById('expensePieChart')
    if (chartDom) {
      const containerWidth = chartDom.offsetWidth || chartDom.clientWidth
      const containerHeight = chartDom.offsetHeight || chartDom.clientHeight
      
      if (containerWidth > 0 && containerHeight > 0) {
        expensePieChart.value.resize({
          width: containerWidth,
          height: containerHeight
        })
      }
    }
  }
}

// 销毁图表
const disposeCharts = () => {
  if (incomeExpenseChart.value) {
    incomeExpenseChart.value.dispose()
    incomeExpenseChart.value = null
  }
  if (expensePieChart.value) {
    expensePieChart.value.dispose()
    expensePieChart.value = null
  }
}

// 报表方法
const generateReport = () => {
  reportDialogVisible.value = true
}

const exportReport = () => {
  ElMessage.info('导出财务报表...')
}

// 分页方法
const handleBudgetPagination = (pagination: any) => {
  budgetPagination.page = pagination.page
  budgetPagination.pageSize = pagination.limit
  loadBudgetData()
}

const handleIncomePagination = (pagination: any) => {
  incomePagination.page = pagination.page
  incomePagination.pageSize = pagination.limit
  loadIncomeData()
}

const handleExpensePagination = (pagination: any) => {
  expensePagination.page = pagination.page
  expensePagination.pageSize = pagination.limit
  loadExpenseData()
}

// 对话框确认
const handleFormConfirm = () => {
  formDialogVisible.value = false
  ElMessage.success('操作成功')
}

// 组件挂载
onMounted(() => {
  // 初始化图表
  initCharts()
  // 生成列表数据
  loadBudgetData()
  loadIncomeData()
  loadExpenseData()
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
  // 销毁图表
  disposeCharts()
})
</script>

<style scoped>
.fund-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stats-card {
  height: 120px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stats-icon.budget {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stats-icon.income {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.stats-icon.expense {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.stats-icon.balance {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stats-icon .el-icon {
  font-size: 24px;
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.main-content {
  background: white;
  border-radius: 8px;
}

.tab-content {
  padding: 20px 0;
}

.query-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}



.amount-text {
  font-weight: 600;
  font-family: 'Courier New', monospace;
}

.income-amount {
  color: #67c23a;
}

.expense-amount {
  color: #f56c6c;
}

.report-charts {
  margin-bottom: 24px;
}

.report-charts .el-card {
  height: 100%;
  min-height: 340px; /* 确保卡片有足够的最小高度 */
}

.report-charts .el-card__body {
  padding: 20px;
  height: calc(100% - 60px);
  min-height: 340px; /* 确保内容区域有足够的最小高度 */
  display: flex;
  flex-direction: column;
}

.report-charts #incomeExpenseChart,
.report-charts #expensePieChart {
  width: 100% !important;
  height: 300px !important;
  min-height: 300px;
  flex: 1;
  /* 确保容器有明确的尺寸 */
  box-sizing: border-box;
}

.report-data {
  margin-top: 24px;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-progress-bar__outer) {
  border-radius: 4px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>